package com.service.bracelet.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.service.bracelet.common.CommonResult;
import com.service.bracelet.export.ExportDataToExcel;
import com.service.bracelet.service.ILumenService;
import com.service.bracelet.util.JwtTokenUtil;
import com.service.bracelet.util.UtilConsts;

@RestController
@RequestMapping("/lumen")
public class LumenController {

	@Autowired
	private ILumenService lumenService;

	/**
	 * 批量增加流明数据
	 */
	@PostMapping(value = "/add")
	public CommonResult<Void> add(@RequestBody Map<String, Object> params, HttpServletRequest request) {
		try {
			int userId = JwtTokenUtil.getUserId(request);
			lumenService.saveList(userId, params);
			return CommonResult.success();
		} catch (Exception e) {
			return CommonResult.error(e);
		}
	}

	/**
	 * 查询所有流明数据
	 */
	@PostMapping(value = "/queryList")
	public CommonResult<List<Map<String, Object>>> queryList(@RequestBody Map<String, Object> params,
			HttpServletRequest request) {
		try {
			JwtTokenUtil.checkAdmin(request);
			return lumenService.queryList(params);
		} catch (Exception e) {
			return CommonResult.error(e);
		}
	}

	/**
	 * 根据条件查询流明数据
	 */
	@PostMapping(value = "/queryMyLumen")
	public CommonResult<List<Map<String, Object>>> queryMyLumen(@RequestBody Map<String, Object> params,
			HttpServletRequest request) {
		try {
			params.put(UtilConsts.PARAMS_USERID, JwtTokenUtil.getUserId(request));
			return lumenService.queryList(params);
		} catch (Exception e) {
			return CommonResult.error(e);
		}
	}

	/**
	 * 根据条件导出流明数据，统计每段流明的数据量
	 * 
	 * @throws IOException
	 */
	@PostMapping(value = "/exportLumen")
	public void exportLumen(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		JwtTokenUtil.checkAdmin(request);

		String name = UtilConsts.EXPORT_FILENAME;
		name += '_' + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name + ".xlsx", "UTF-8"));

		ServletOutputStream out = response.getOutputStream();
		List<Object[]> datas = lumenService.queryExportData(params);

		String fileName = UtilConsts.EXPORT_FILENAME;
		String[] columnNames = UtilConsts.EXOPRT_COLUMNNAMES;
		try (ExportDataToExcel export = new ExportDataToExcel()) {
			export.exportData(fileName, columnNames, datas, true);
			export.write(out);
		}

		out.flush();
	}

	/**
	 * 根据条件查询流明数据，统计每段流明的数据量
	 * 
	 * @param params
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "/queryExportLumen")
	public CommonResult<List<Object[]>> queryExportLumen(@RequestBody Map<String, Object> params,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		JwtTokenUtil.checkAdmin(request);
		try {
			return CommonResult.success(lumenService.queryExportData(params));
		} catch (Exception e) {
			return CommonResult.error(e);
		}
	}

	/**
	 * 根据条件导出流明数据，每5分钟做一个平均值
	 * 
	 * @throws IOException
	 */
	@PostMapping(value = "/exportLumenForAvg")
	public void exportLumenForAvg(@RequestBody Map<String, Object> params, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		JwtTokenUtil.checkAdmin(request);

		String name = UtilConsts.EXPORT_FILENAME_AVG;
		name += '_' + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		response.setContentType("application/vnd.ms-excel;charset=utf-8");
		response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(name + ".xlsx", "UTF-8"));

		ServletOutputStream out = response.getOutputStream();
		List<Object[]> datas = lumenService.queryExportDataForAvg(params);

		// 计算导出的列数据
		String fileName = UtilConsts.EXPORT_FILENAME_AVG;
		int segment = 12 * 24; // 一天时间分288段
		int comm = UtilConsts.EXOPRT_COLUMNNAMES_SVG.length; // 通用列数，即7列
		int total = segment + comm; // 总共295列
		String[] columnNames = new String[total];
		System.arraycopy(UtilConsts.EXOPRT_COLUMNNAMES_SVG, 0, columnNames, 0, comm);
		int hour = 0;
		int minute = 0;
		for (int i = 0; i < segment; i++) {
			String time = (hour < 10 ? "0" + hour : hour) + ":" + (minute < 10 ? "0" + minute : minute);
			columnNames[comm + i] = time;
			minute += 5;
			if (minute >= 60) {
				minute = 0;
				hour += 1;
			}
		}
		try (ExportDataToExcel export = new ExportDataToExcel()) {
			export.exportData(fileName, columnNames, datas, false);
			export.write(out);
		}

		out.flush();
	}

	/**
	 * 根据条件查询流明数据，每5分钟做一个平均值
	 * 
	 * @param params
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "/queryExportLumenForAvg")
	public CommonResult<List<Object[]>> queryExportLumenForAvg(@RequestBody Map<String, Object> params,
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		JwtTokenUtil.checkAdmin(request);
		try {
			return CommonResult.success(lumenService.queryExportDataForAvg(params));
		} catch (Exception e) {
			return CommonResult.error(e);
		}
	}
}
